package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;

/**
 * Title  : 114. Flatten Binary Tree to Linked List
 * Source : https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-09-05
 */

public class LeetCode_114 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        ArrayDeque<TreeNode> sta = new ArrayDeque<>();
        TreeNode current = root, next;
        sta.push(root);
        while (!sta.isEmpty()) {
            next = sta.pop();
            if (next.right != null) {
                sta.push(next.right);
            }

            if (next.left != null) {
                sta.push(next.left);
            }
            if (next != root) {
                current.left = null;
                current.right = next;
                current = next;
            }
        }
    }
}
